const { list, fmData } = require("./mock");
const Mock = require('mockjs')
const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken');
const userList = [{
  username: '123@qq.com',
  password: '123456',
  nickname: '小三三',
  avator: Mock.mock('@image(30x30, @color)'),
},{
  username: '13111111111',
  password: '654321',
  nickname: '李四',
  avator: Mock.mock('@image(30x30, @color)'),
}]
module.exports = (app) => {
  app.use(bodyParser.json())
  app.get("/api/list", (req, res) => {
    const { pageCode = 1, pageSize = 10 } = req.query;
    if (pageCode * pageSize <= list.length)
      res.send({
        code: 200,
        data: list.slice((pageCode - 1) * pageSize, pageCode * pageSize),
				message: '成功加载10条数据！'
      });
    else
      res.send({
        code: 201,
        data: null,
				message: '没有更多数据了！！'
      });
  });

  app.get('/api/detail', (req, res) => {
    const { id } = req.query;
    const item = list.find(v => v.id ===id)
    res.send({
      code: 200,
      data: item
    })
  })

  app.get('/api/fm/data', (req, res) => {
    res.send({
      code: 200,
      data: fmData
    })
  })

  app.post('/api/login', (req, res) => {
    const { username, password } = req.body;
    const user = userList.find(v => v.username === username && password === v.password)

    if(user) {
      res.send({
        code: 200,
        message: '登录成功， 欢迎' + user.nickname,
        data: {
          nickname: user.nickname,
          avator: user.avator,
          token: JWT.sign({ nickname: user.nickname, avator: user.avator, username: user.username }, '666666')
        }
      })
    } else {
      res.send({
        code: 401,
        message: '账户密码错误， 请重新登录',
        data: null
      })
    }
  })
};
